package com.dfdchem.imd.kaiwu.activity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.PopupMenu;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.dfdchem.imd.kaiwu.R;
import com.dfdchem.imd.kaiwu.activity.base.BaseActivity;
import com.dfdchem.imd.kaiwu.constant.RouterPath;
import com.dfdchem.imd.kaiwu.util.VersionUtil;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.AgentWebConfig;
import com.just.agentweb.DefaultWebClient;
import com.just.agentweb.WebChromeClient;
import com.just.agentweb.WebViewClient;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;


/**
 * 新闻/文章页面，其实和WebViewActivity差不多
 */
@Route(path = RouterPath.NEWS_DETAIL_ACTIVITY)
public class NewsDetailActivity extends BaseActivity implements View.OnClickListener, PopupMenu.OnMenuItemClickListener, OnRefreshListener {

    private static final String TAG = "NewsDetailActivity";

    @Autowired
    String title;

    @Autowired
    String url;

    @Autowired
    boolean full_screen = false;

    private TextView mTitleTextView;
    private AgentWeb mAgentWeb;
    private LinearLayout mLinearLayout;
    private View iv_back;
    private View iv_more;
    private View webview_tool_bar;

    private PopupMenu mPopupMenu;
    private RefreshLayout refreshLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_detail);

        initView();
        initData();
        initEvent();
    }

    @Override
    public void initView() {
        mTitleTextView = findView(R.id.web_view_toolbar_title);
        mLinearLayout = findView(R.id.webView_layout);
        webview_tool_bar = findView(R.id.webview_tool_bar);
        if (full_screen) {
            webview_tool_bar.setVisibility(View.GONE);
        }
        iv_back = findView(R.id.iv_back);
        iv_more = findView(R.id.iv_more);

        refreshLayout = (RefreshLayout) findViewById(R.id.refreshLayout);
    }

    /**
     * 显示更多菜单
     *
     * @param view 菜单依附在该View下面
     */
    private void showPoPup(View view) {
        if (mPopupMenu == null) {
            mPopupMenu = new PopupMenu(this.getActivity(), view);
            mPopupMenu.inflate(R.menu.webview_toolbar_menu);
            mPopupMenu.setOnMenuItemClickListener(this);
        }
        mPopupMenu.show();
    }

    @Override
    public void initData() {
        mTitleTextView.setText(title);

        if (mAgentWeb == null) {
            mAgentWeb = AgentWeb.with(this)
                    .setAgentWebParent(mLinearLayout, new LinearLayout.LayoutParams(-1, -1))
                    .useDefaultIndicator()
                    .setWebChromeClient(mWebChromeClient)
                    .setWebViewClient(mWebViewClient)
                    .setMainFrameErrorView(R.layout.agentweb_error_page, -1)
                    .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                    .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK)//打开其他应用时，弹窗咨询用户是否前往其他应用
                    .interceptUnkownUrl() //拦截找不到相关页面的Scheme
                    .createAgentWeb()
                    .ready()
                    .go(url);
            WebSettings webSettings = mAgentWeb.getAgentWebSettings().getWebSettings();
            String ua = webSettings.getUserAgentString();
            ua += getResources().getString(R.string.app_host) + "/" + VersionUtil.getAppVersionName(this);;
            webSettings.setUserAgentString(ua);
            Log.d(TAG, "UA:" + webSettings.getUserAgentString());
        }

    }

    @Override
    public void initEvent() {
        iv_more.setOnClickListener(this);
        iv_back.setOnClickListener(this);
        refreshLayout.setOnRefreshListener(this);
    }

    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (mTitleTextView != null) {
                mTitleTextView.setText(title);
            }
        }
    };

    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            //do you  work
            Log.i("Info", "WebViewActivity onPageStarted");
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_more:
                showPoPup(v);
                break;
            case R.id.iv_back:
                onBackPressed();
                break;
        }
    }

    @Override
    public void onReturnClick(View v) {
        enterAnim = R.anim.left_push_in;
        exitAnim = R.anim.right_push_out;
        this.finish();
    }

    @Override
    public void onBackPressed() {
        if (mAgentWeb.getWebCreator().getWebView().canGoBack()) {
            mAgentWeb.back();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {

            case R.id.refresh:
                if (mAgentWeb != null) {
                    mAgentWeb.getUrlLoader().reload(); // 刷新
                }
                return true;

            case R.id.copy:
                if (mAgentWeb != null) {
                    toCopy(this, mAgentWeb.getWebCreator().getWebView().getUrl());
                    showShortToast("复制链接成功");
                }
                return true;
            case R.id.default_browser:
                if (mAgentWeb != null) {
                    openBrowser(mAgentWeb.getWebCreator().getWebView().getUrl());
                }
                return true;
            case R.id.default_clean:
                toCleanWebCache();
                return true;
            case R.id.error_website:
                loadErrorWebSite();
                return true;
            default:
                return false;
        }
    }

    /**
     * 复制字符串
     *
     * @param context
     * @param text
     */
    private void toCopy(Context context, String text) {

        ClipboardManager mClipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        mClipboardManager.setPrimaryClip(ClipData.newPlainText(null, text));

    }

    /**
     * 打开浏览器
     *
     * @param targetUrl 外部浏览器打开的地址
     */
    private void openBrowser(String targetUrl) {
        if (TextUtils.isEmpty(targetUrl) || targetUrl.startsWith("file://") || targetUrl.startsWith("kaiwu://")) {
            Toast.makeText(this, targetUrl + " 该链接无法使用浏览器打开。", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        Uri mUri = Uri.parse(targetUrl);
        intent.setData(mUri);
        startActivity(intent);
    }

    /**
     * 测试错误页的显示
     */
    private void loadErrorWebSite() {
        if (mAgentWeb != null) {
            mAgentWeb.getUrlLoader().loadUrl("http://www.unkownwebsiteblog.me");
        }
    }

    /**
     * 清除 WebView 缓存
     */
    private void toCleanWebCache() {
        if (this.mAgentWeb != null) {
            //清理所有跟WebView相关的缓存 ，数据库， 历史记录 等。
            this.mAgentWeb.clearWebCache();
            Toast.makeText(getActivity(), "已清理缓存", Toast.LENGTH_SHORT).show();
            //清空所有 AgentWeb 硬盘缓存，包括 WebView 的缓存 , AgentWeb 下载的图片 ，视频 ，apk 等文件。
            AgentWebConfig.clearDiskCache(this);
        }

    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        if (mAgentWeb != null) {
            mAgentWeb.getUrlLoader().reload(); // 刷新
            refreshLayout.finishRefresh(500);
        }
    }
}
